package me.imli.app.ui;

import me.imli.app.R;
import me.imli.app.widget.SwipeLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@EActivity(R.layout.activity_web)
public class WebActivity extends BaseActivity {
	
	public static final String INTENT_URL = "intent_url";
	
	private String mUrl;
	
	@ViewById(R.id.swl_web)
	SwipeLayout mSwipeLayout;

	@ViewById(R.id.web)
	WebView mWebView;
	
	@AfterViews
	void init() {
		mSwipeLayout.setOnRefreshListener(onRefreshListener());
		mSwipeLayout.setRefreshing(true);
		
		mUrl = getIntent().getStringExtra(INTENT_URL);

		WebSettings mWebSettings = mWebView.getSettings();
		mWebSettings.setJavaScriptEnabled(true);
		mWebSettings.setDomStorageEnabled(true);
		mWebSettings.setDefaultTextEncodingName("UTF-8"); 
		mWebView.setWebViewClient(new ImliWebViewClinet());
		mWebView.setWebChromeClient(new ImliWebChromeClinet());
		mWebView.loadUrl(mUrl);
		setTitle(mUrl);
	}
	
	private OnRefreshListener onRefreshListener() {
		return new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				mWebView.reload();
			}
		};
	}
	
	private class ImliWebViewClinet extends WebViewClient {
		
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if(url.indexOf("tel:")<0){
				//页面上有数字会导致连接电话  
				view.loadUrl(url);
				view.reload();
			}
			return true;
		}
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (!mSwipeLayout.isRefreshing()) {
				mSwipeLayout.setRefreshing(true);
			}
			super.onPageStarted(view, url, favicon);
		}
		
		@Override
		public void onPageFinished(WebView view, String url) {
			mSwipeLayout.setRefreshing(false);
			super.onPageFinished(view, url);
		}
		
		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			mSwipeLayout.setRefreshing(false);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
		
		@Override
		public void onScaleChanged(WebView view, float oldScale, float newScale) {
			// super.onScaleChanged(view, oldScale, newScale);
		}
	}
	
	private class ImliWebChromeClinet extends WebChromeClient {
		
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress < 100 && newProgress >= 0) {
			} else if (newProgress >= 100) {
			}
			super.onProgressChanged(view, newProgress);
		}
		
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus) {
		}
	}
	
}
